package com.hsl.housaileibot001.listener;

import cn.tbox.sdk.core.exception.TboxClientConfigException;
import cn.tbox.sdk.core.exception.TboxHttpResponseException;
import com.hsl.housaileibot001.ai.bailing.BailingChatService;
import com.hsl.housaileibot001.document.MockQuestion;
import com.hsl.housaileibot001.model.dto.BailingGenerateMockExamDTO;
import com.hsl.housaileibot001.model.dto.MockExamGenerationMessage;
import com.hsl.housaileibot001.model.vo.MockExamVO;
import com.hsl.housaileibot001.service.MockExamGenerationTaskService;
import com.hsl.housaileibot001.service.MockQuestionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

/**
 * Kafka Consumer 监听器
 */
@Component
public class MockExamGenerationConsumer {

    private static final Logger logger = LoggerFactory.getLogger(MockExamGenerationConsumer.class);

    @Autowired
    private BailingChatService bailingChatService;

    @Autowired
    private MockQuestionService mockQuestionService;

    @Autowired
    private MockExamGenerationTaskService taskService;

    @KafkaListener(topics = "${kafka.topic.mock-exam-generation:mock-exam-generation}", 
                   groupId = "mock-exam-consumer-group")
    public void consumeMessage(@Payload MockExamGenerationMessage message,
                               @Header(KafkaHeaders.RECEIVED_TOPIC) String topic,
                               Acknowledgment acknowledgment) {
        String taskId = message.getTaskId();
        Long interviewQuestionId = message.getInterviewQuestionId();
        
        logger.info("开始处理消息: taskId={}, interviewQuestionId={}", taskId, interviewQuestionId);
        
        try {
            // 更新任务状态为 PROCESSING（如果是第一条消息）
            var task = taskService.getTaskById(taskId);
            if (task != null && "PENDING".equals(task.getStatus())) {
                taskService.updateTaskStatus(taskId, "PROCESSING");
                if (task.getStartTime() == null) {
                    // 设置开始时间
                    task.setStartTime(java.time.LocalDateTime.now());
                }
            }
            
            // 检查是否已有模拟题（缓存）
            var existingQuestions = mockQuestionService.findActiveByInterviewQuestionId(interviewQuestionId);
            if (existingQuestions != null && !existingQuestions.isEmpty()) {
                logger.info("题目已有模拟题，跳过生成: taskId={}, interviewQuestionId={}", taskId, interviewQuestionId);
                taskService.incrementCompleted(taskId);
                acknowledgment.acknowledge();
                return;
            }
            
            // 构建请求DTO
            BailingGenerateMockExamDTO requestDTO = new BailingGenerateMockExamDTO();
            requestDTO.setAppId(message.getAppId());
            requestDTO.setUserId(message.getUserId());
            requestDTO.setUserMessage(message.getUserMessage());
            
            // 调用白凌接口生成模拟题
            MockExamVO mockExam = bailingChatService.generateMockExam(requestDTO);
            mockExam.setInterviewQuestionId(interviewQuestionId);
            
            // 保存模拟题到 MongoDB
            if (mockExam.getMockQuestions() != null && !mockExam.getMockQuestions().isEmpty()) {
                for (MockExamVO.MockQuestion mockQuestionVO : mockExam.getMockQuestions()) {
                    try {
                        MockQuestion mockQuestion = new MockQuestion(interviewQuestionId, mockQuestionVO);
                        mockQuestionService.save(mockQuestion);
                    } catch (Exception e) {
                        logger.error("保存模拟题到MongoDB失败: taskId={}, interviewQuestionId={}", 
                                taskId, interviewQuestionId, e);
                    }
                }
            }
            
            // 更新任务进度
            taskService.incrementCompleted(taskId);
            
            // 检查任务是否完成
            var updatedTask = taskService.getTaskById(taskId);
            if (updatedTask != null) {
                int total = updatedTask.getTotalCount();
                int completed = updatedTask.getCompletedCount();
                int failed = updatedTask.getFailedCount();
                
                if (completed + failed >= total && "PROCESSING".equals(updatedTask.getStatus())) {
                    // 所有消息已处理完成
                    if (failed == 0) {
                        taskService.completeTask(taskId);
                    } else {
                        taskService.updateTaskStatus(taskId, "COMPLETED");
                    }
                }
            }
            
            logger.info("消息处理成功: taskId={}, interviewQuestionId={}", taskId, interviewQuestionId);
            
            // 手动提交 offset
            acknowledgment.acknowledge();
            
        } catch (TboxClientConfigException | TboxHttpResponseException e) {
            logger.error("生成模拟题失败: taskId={}, interviewQuestionId={}", taskId, interviewQuestionId, e);
            taskService.incrementFailed(taskId);
            
            // 检查任务是否完成（失败情况）
            var updatedTask = taskService.getTaskById(taskId);
            if (updatedTask != null) {
                int total = updatedTask.getTotalCount();
                int completed = updatedTask.getCompletedCount();
                int failed = updatedTask.getFailedCount();
                
                if (completed + failed >= total && "PROCESSING".equals(updatedTask.getStatus())) {
                    taskService.updateTaskStatus(taskId, "COMPLETED");
                }
            }
            
            // 即使失败也提交 offset，避免重复处理
            acknowledgment.acknowledge();
        } catch (Exception e) {
            logger.error("处理消息异常: taskId={}, interviewQuestionId={}", taskId, interviewQuestionId, e);
            taskService.incrementFailed(taskId);
            
            // 检查任务是否完成（异常情况）
            var updatedTask = taskService.getTaskById(taskId);
            if (updatedTask != null) {
                int total = updatedTask.getTotalCount();
                int completed = updatedTask.getCompletedCount();
                int failed = updatedTask.getFailedCount();
                
                if (completed + failed >= total && "PROCESSING".equals(updatedTask.getStatus())) {
                    taskService.updateTaskStatus(taskId, "COMPLETED");
                }
            }
            
            acknowledgment.acknowledge();
        }
    }
}

